<template>
  <div class="gi_table_page">
    <GiTable
      title="任务管理"
      row-key="id"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1300 }"
      :pagination="pagination"
      :disabled-tools="[]"
      :disabled-column-keys="['name']"
      @refresh="search"
    >
      <template #toolbar-left>
        <a-input-search v-model="queryForm.title" placeholder="搜索任务名称" allow-clear @search="search" />
        <a-select v-model="queryForm.triggerType" placeholder="请选择调度类型" :options="job_trigger_type_enum" allow-clear style="width: 150px" @change="search" />
        <a-select v-model="queryForm.status" placeholder="请选择任务状态" :options="job_status_enum" allow-clear style="width: 150px" @change="search" />
        <a-button @click="reset">
          <template #icon><icon-refresh /></template>
          <template #default>重置</template>
        </a-button>
      </template>
      <template #toolbar-right>
        <a-button v-permission="['scheduler:job:create']" type="primary" @click="onAdd">
          <template #icon><icon-plus /></template>
          <template #default>新增</template>
        </a-button>
      </template>
      <template v-if="has.hasPermOr(['scheduler:job:view'])" #title="{ record }">
        <a-link @click="onDetail(record)">{{ record.title }}</a-link>
      </template>
      <template #triggerType="{ record }">
        <GiCellTag :value="record.triggerType" :dict="job_trigger_type_enum" />:&nbsp;
        <span v-if="record.triggerType === 1">{{ record.fixedInterval }} 秒</span>
        <span v-else>
          <a-popover title="最近5次运行时间" position="bottom">
            <template #content>
              <a-textarea :model-value="parseCron(record.cron)" :auto-size="true" style="margin-top: 10px" />
            </template>
            <a-link>{{ record.cron }}</a-link>
          </a-popover>
        </span>
      </template>
      <template #status="{ record }">
        <a-switch
          v-model="record.status"
          :checked-value="1"
          :unchecked-value="0"
          :disabled="!has.hasPermOr(['scheduler:job:pause', 'scheduler:job:resume'])"
          @change="onUpdateStatus(record)"
        />
      </template>
      <template #action="{ record }">
        <a-space>
          <a-button v-permission="['scheduler:log:view']" type="primary" status="success" size="mini" title="日志" @click="onLog(record)">日志</a-button>
          <a-popconfirm content="是否确定立即执行一次任务?" type="warning" @ok="onExecute(record)">
            <a-button
              v-permission="['scheduler:job:execute']"
              type="primary" status="normal" size="mini"
              :disabled="record.status === 1"
              :title="record.status === 1 ? '已启用的任务无法执行' : '执行'"
            >
              执行
            </a-button>
          </a-popconfirm>
          <a-button v-permission="['scheduler:job:update']" type="primary" status="warning" size="mini" title="修改" @click="onUpdate(record)">修改</a-button>
          <a-button
            v-permission="['scheduler:job:delete']"
            type="primary" status="danger" size="mini"
            :disabled="record.isSystem"
            :title="record.isSystem ? '系统内置数据不能删除' : '删除'" @click="onDelete(record)"
          >
            删除
          </a-button>
        </a-space>
      </template>
    </GiTable>

    <JobAddModal ref="JobAddModalRef" @save-success="reset" />
    <JobDetailDrawer ref="JobDetailDrawerRef" />
  </div>
</template>

<script setup lang="ts">
import { Message, type TableInstance } from '@arco-design/web-vue'
import { useRouter } from 'vue-router'
import JobAddModal from './JobAddModal.vue'
import JobDetailDrawer from './JobDetailDrawer.vue'
import { type JobQuery, type JobResp, deleteJob, executeJob, pageJob, pauseJob, resumeJob } from '@/apis/scheduler'
import { useTable } from '@/hooks'
import { useDict } from '@/hooks/app'
import { isMobile, parseCron } from '@/utils'
import has from '@/utils/has'

defineOptions({ name: 'SchedulerJob' })

const { job_status_enum, job_trigger_type_enum } = useDict('job_status_enum', 'job_trigger_type_enum')

const queryForm = reactive<JobQuery>({
})

const {
  tableData: dataList,
  loading,
  pagination,
  search,
  handleDelete
} = useTable((page) => pageJob({ ...queryForm, ...page }), { immediate: true })
const columns: TableInstance[] = [
  {
    title: '序号',
    width: 50,
    align: 'center',
    render: ({ rowIndex }) => h('span', {}, rowIndex + 1 + (pagination.current - 1) * pagination.pageSize)
  },
  { title: '任务标题', dataIndex: 'title', slotName: 'title', width: 100, ellipsis: true, tooltip: true },
  { title: '任务类名', dataIndex: 'jobClassName', slotName: 'jobClassName', width: 250, ellipsis: true, tooltip: true },
  { title: '调度类型', dataIndex: 'triggerType', slotName: 'triggerType', width: 150 },
  { title: '状态', dataIndex: 'status', width: 100, slotName: 'status', align: 'center' },
  { title: '描述', dataIndex: 'description', width: 180, ellipsis: true, tooltip: true },
  { title: '创建时间', dataIndex: 'createTime', width: 130 },
  {
    title: '操作',
    slotName: 'action',
    width: 200,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined,
    show: has.hasPermOr([
      'scheduler:log:view',
      'scheduler:job:execute',
      'scheduler:job:update',
      'scheduler:job:delete'
    ])
  }
]

// 重置
const reset = () => {
  queryForm.title = undefined
  queryForm.triggerType = undefined
  queryForm.status = undefined
  search()
}

// 删除
const onDelete = (record: JobResp) => {
  return handleDelete(() => deleteJob(record.id), {
    content: `是否确定删除任务「${record.title}」？`,
    showModal: true
  })
}

// 修改状态
const onUpdateStatus = (record: JobResp) => {
  if (record.status === 1) {
    resumeJob(record.id)
      .then(() => {
        Message.success('启用成功')
      }).catch(() => {
        record.status = record.status === 1 ? 0 : 1
      })
  } else {
    pauseJob(record.id)
      .then(() => {
        Message.success('禁用成功')
      }).catch(() => {
        record.status = record.status === 0 ? 1 : 0
      })
  }
}

// 执行
const onExecute = (record: JobResp) => {
  executeJob(record.id).then(() => {
    Message.success('执行请求已下发')
  })
}

const JobAddModalRef = ref<InstanceType<typeof JobAddModal>>()
// 新增
const onAdd = () => {
  JobAddModalRef.value?.onAdd()
}

// 修改
const onUpdate = (record: JobResp) => {
  JobAddModalRef.value?.onUpdate(record)
}

const JobDetailDrawerRef = ref<InstanceType<typeof JobDetailDrawer>>()
// 详情
const onDetail = (record: JobResp) => {
  JobDetailDrawerRef.value?.onOpen(record)
}

const router = useRouter()
// 日志
const onLog = (record: JobResp) => {
  router.push({ path: '/scheduler/log', query: { jobId: record.id, title: record.title } })
}
</script>

<style scoped lang="scss"></style>
